from django.db.models.fields.reverse_related import ManyToOneRel, ManyToManyRel, OneToOneRel

# 类型转换
type_conversion_dict = {
    "CharField": "short_string",
    "EmailField": 'short_string',
    "UUIDField": 'short_string',
    "TextField": "long_string",
    "FloatField": "float",
    "IntegerField": "int",
    "PositiveIntegerField": "int",
    "BooleanField": "bool",
    "DateTimeField": "datetime",
    'DateField': 'datetime',
    "operate": "operate",
    "ForeignKey": "foreignkey",
    "ManyToManyField": "relation",
}

def emptyValue(item):
    return item is None or item == ""

# 从序列化获取model的配置
def get_model_serializer_config(serializer):
    config_data = []
    serializer_model = serializer.Meta.model
    model_fields = [field.name for field in serializer_model._meta.get_fields() if not isinstance(field, (ManyToOneRel, ManyToManyRel, OneToOneRel))]
    if hasattr(serializer.Meta,"fields"):
        serializer_fields = serializer.Meta.fields
    elif hasattr(serializer.Meta,"exclude"):
        serializer_fields = [field for field in model_fields if field not in serializer.Meta.exclude]
    
    for field_name in serializer_fields:
        if field_name in model_fields:
            field = serializer_model._meta.get_field(field_name)
            field_info = {
                "title":field.verbose_name,
                "dataIndex":field.name,
                "type":field.get_internal_type()
            }
            if not field.null:
                field_info["required"] = True
            config_data.append(field_info)
        else :
            config_data.append({
                "title":None,
                "dataIndex":field_name,
                "type":None
            })
    return config_data


# 将序列化的错误进行包装
def handle_serializer_error(errors):
    custom_errors = []
    # print(errors)
    for field, error_details in errors.items():
        for error in error_details:
            if error.code == 'unique':
                error_content = str(error).split("this")[1]
                custom_errors.append(error_content)
            else:
                custom_errors.append(error)
    formatted_errors = "\n".join(str(error) for error in custom_errors)
    return formatted_errors